<script setup lang="ts">
import { computed, onMounted, onUnmounted, PropType, ref, watchEffect, nextTick } from 'vue'
import echarts, { ECOption } from './config'

const chartRef = ref<HTMLElement | null>(null)
let myChart: echarts.ECharts | null = null

const props = defineProps({
	width: {
		type: String,
		default: '100%'
	},
	height: {
		type: String,
		default: '100%'
	},
	chartData: {
		type: Object as PropType<{
			subject: string[]
			passRate: number[] // 及格率数据（百分比）
			excellentRate: number[] // 优秀率数据（百分比）
			violationCount?: number[] // 违规人数
			title?: string // 可选的标题
		}>
	}
})

// 分组柱状图配置
const barOption = computed(
	(): ECOption => ({
		title: {
			text: props.chartData?.title || '成绩',
			left: 'center',
			top: '0',
			textStyle: {
				color: '#409EFF',
				fontSize: 16,
				fontWeight: 'normal'
			}
		},
		legend: {
			data: ['及格率', '优秀率', '违规人数'],
			icon: 'circle',
			right: 'right'
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			},
			formatter: function (params: any) {
				return (
					params[0].name +
					'<br/>' +
					params
						.map((item: any) => {
							// 为违规人数添加特殊格式
							if (item.seriesName === '违规人数') {
								return item.seriesName + ': ' + item.value + ' 人'
							}
							return item.seriesName + ': ' + item.value + '%'
						})
						.join('<br/>')
				)
			}
		},
		grid: {
			left: '40',
			right: '100',
			bottom: '30'
		},
		xAxis: {
			name: '科目',
			type: 'category',
			data: props.chartData?.subject
		},
		yAxis: [
			{
				name: '百分比', // 左侧Y轴 - 百分比
				type: 'value',
				max: 100,
				axisLabel: {
					formatter: '{value}%'
				}
			},
			{
				// name: '人数', // 右侧Y轴 - 违规人数
				type: 'value',
				max: props.chartData?.violationCount
					? Math.max(...props.chartData.violationCount) * 1.2
					: 10,
				splitLine: {
					show: false
				},
				axisLine: {
					lineStyle: {
						color: '#E06666' // 红色
					}
				},
				// 坐标轴配置
				axisLabel: {
					show: false,
					formatter: '{value} 人',
					color: '#E06666'
				}
			}
		],
		series: [
			{
				name: '及格率',
				data: props.chartData?.passRate,
				type: 'bar',
				barGap: 0.1,
				itemStyle: {
					color: '#5470C6'
				},
				label: {
					show: true,
					position: 'top',
					fontSize: '12',
					formatter: function (params: any) {
						return `${params.value}%`
					}
				}
			},
			{
				name: '优秀率',
				data: props.chartData?.excellentRate,
				type: 'bar',
				itemStyle: {
					color: '#91CC75'
				},
				label: {
					show: true,
					position: 'top',
					fontSize: '12',
					formatter: function (params: any) {
						return `${params.value}%`
					}
				}
			},
			{
				name: '违规人数',
				data: props.chartData?.violationCount,
				type: 'line',
				yAxisIndex: 1, // 使用右侧Y轴
				symbol: 'circle',
				symbolSize: 8,
				lineStyle: {
					width: 3,
					color: '#E06666' // 红色
				},
				itemStyle: {
					color: '#E06666'
				},
				label: {
					show: true,
					position: 'top',
					fontSize: '12',
					formatter: function (params: any) {
						return params.value
					}
				}
			}
		]
	})
)

const echartsStyle = {
	width: props.width,
	height: props.height
}

// 销毁图表实例
function disposeChart() {
	if (myChart) {
		try {
			// 移除事件监听
			window.removeEventListener('resize', handleResize)
			myChart.dispose()
		} catch (e) {
			console.error('销毁图表实例失败:', e)
		} finally {
			myChart = null
		}
	}
}

function initChart() {
	console.log('初始化图表实例，先确保销毁现有实例')
	// 确保先销毁现有实例
	disposeChart()

	if (!chartRef.value) {
		console.error('图表容器不存在')
		return
	}

	// 确保DOM已经渲染
	nextTick(() => {
		// 检查容器尺寸
		if (chartRef.value && chartRef.value.clientWidth > 0 && chartRef.value.clientHeight > 0) {
			try {
				console.log('创建新的图表实例')
				// 检查是否已经有echarts实例绑定到这个DOM
				const existingInstance = echarts.getInstanceByDom(chartRef.value)
				if (existingInstance) {
					console.warn('DOM上已存在图表实例，先销毁')
					existingInstance.dispose()
				}

				myChart = echarts.init(chartRef.value)
				myChart.setOption(barOption.value)

				// 添加窗口调整大小事件监听
				window.addEventListener('resize', handleResize)
			} catch (e) {
				console.error('初始化图表失败:', e)
			}
		} else {
			console.warn('图表容器尺寸为0，延迟初始化')
			// 延迟初始化
			setTimeout(() => {
				if (chartRef.value) {
					try {
						// 再次检查是否有实例
						const existingInstance = echarts.getInstanceByDom(chartRef.value)
						if (existingInstance) {
							console.warn('DOM上已存在图表实例，先销毁')
							existingInstance.dispose()
						}

						myChart = echarts.init(chartRef.value)
						myChart.setOption(barOption.value)
						window.addEventListener('resize', handleResize)
					} catch (e) {
						console.error('延迟初始化图表失败:', e)
					}
				}
			}, 300)
		}
	})
}

function handleResize() {
	if (myChart) {
		myChart.resize()
	}
}

// 更新图表
function updateChart() {
	if (myChart) {
		try {
			myChart.setOption(barOption.value, true)
		} catch (e) {
			console.error('更新图表失败，尝试重新初始化:', e)
			initChart()
		}
	} else {
		// 如果图表未初始化，则初始化
		initChart()
	}
}

onMounted(() => {
	console.log('图表组件挂载')
	// 使用setTimeout确保DOM完全渲染
	setTimeout(() => {
		initChart()
	}, 100)
})

// 组件更新时
watchEffect(() => {
	if (props.chartData) {
		console.log('图表数据更新，准备更新图表')
		// 延迟更新，确保DOM已更新
		setTimeout(() => {
			updateChart()
		}, 100)
	}
})

onUnmounted(() => {
	console.log('图表组件卸载')
	disposeChart()
})
</script>

<template>
	<div ref="chartRef" :style="echartsStyle" class="echart-container"></div>
</template>

<style scoped>
.echart-container {
	min-height: 300px;
	min-width: 200px;
}
</style>
